package com.xx.ViewInfo;

import com.xx.hdfs.HdfsDemo;
import com.xx.hdfs.HdfsLog;
import com.xx.hdfsFx.promptStage.ErrorPrompt;
import javafx.animation.FadeTransition;
import javafx.geometry.Pos;
import javafx.scene.control.Tab;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.util.Duration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileViewItem extends Tab {
    private AnchorPane root;
    public HdfsView hdfsView;
    HdfsDemo hdfsDemo;
    Path path;
    private ImageView icon;
    private Text t;
    private ImageView close;
    private final Image closeOut;
    private final Image closeIn;
    private final Image iconI;
    private final Image barI;

    private Image TeditI;
    private Image TSaveI;
    private Image TAllI;
    private Image TcopyI;
    private Image TstickupI;
    private Image TquitI;
    private Image TcutI;
    private ImageView bar;
    private Font in;
    private Font out;
    public TextAreaView area;
    private boolean isPreview = false;
    private Color choiceColor = Color.SLATEBLUE;
    private HdfsLog log;

    public FileViewItem(AnchorPane root, HdfsView hdfsView, HdfsDemo hdfsDemo,
                        Image closeIn, Image closeOut,
                        Image barI, Image iconI, Image TeditI, Image Tsavei
            , Image TAllI, Image TcopyI, Image TstickupI, Image TquitI, Image TcutI, HdfsLog log) {
        this.log = log;
        this.root = root;
        this.hdfsDemo = hdfsDemo;
        this.hdfsView = hdfsView;
        this.path = hdfsView.status.getPath();
        this.closeIn = closeIn;
        this.closeOut = closeOut;
        this.barI = barI;
        this.iconI = iconI;
        this.TAllI = TAllI;
        this.TeditI = TeditI;
        this.TSaveI = Tsavei;
        this.TcopyI = TcopyI;
        this.TstickupI = TstickupI;
        this.TquitI = TquitI;
        this.TcutI = TcutI;

        initView();
        viewAction();
        closeAction();
        textInfo();

        this.selectedProperty().addListener((ob, ov, nv) -> {
            if (nv) onChoice();
            else onNotChoice();
        });
    }


    public void initView() {
        icon = new ImageView(iconI);
        icon.setPreserveRatio(true);
        icon.setFitWidth(30);
        icon.setTranslateY(5);

        t = new Text(hdfsView.status.getPath().getName());
        in = new Font(20);
        out = new Font(20);
        t.setFont(out);

        close = new ImageView(closeOut);
        close.setPreserveRatio(true);
        close.setTranslateY(5);
        close.setFitWidth(30);

        bar = new ImageView(barI);

        HBox hb = new HBox(5);
        hb.setAlignment(Pos.BASELINE_LEFT);
        VBox vb = new VBox(15);
        hb.getChildren().addAll(icon, t, close);
        vb.getChildren().addAll(hb, this.bar);
        setGraphic(vb);
    }

    public void onChoice() {
        t.setFont(in);
        t.setFill(choiceColor);
        bar.setVisible(true);
        close.setVisible(true);
    }

    public void onNotChoice() {
        t.setFont(out);
        t.setFill(Color.BLACK);
        bar.setVisible(false);
        close.setVisible(false);
    }

    public void viewAction() {
        getGraphic().setOnMouseEntered(event -> {
            if (isSelected()) return;
            t.setFont(in);
            t.setFill(Color.LIGHTSKYBLUE);
            close.setVisible(true);
        });
        getGraphic().setOnMouseExited(event -> {
            if (isSelected()) return;
            t.setFont(out);
            t.setFill(Color.BLACK);
            close.setVisible(false);
        });
    }

    public void closeAction() {
        close.setOnMouseEntered(event -> {
            close.setImage(closeIn);
        });
        close.setOnMouseExited(event -> {
            close.setImage(closeOut);
        });
        close.setOnMouseClicked(event -> {
            if (event.getButton().equals(MouseButton.PRIMARY)) {
                itemClose();
                event.consume();
            }
        });
    }

    private void itemClose() {
        area.clear();
        getTabPane().getTabs().remove(this);
        setContent(null);
        System.gc();
    }

    private void textInfo() {
        area = new TextAreaView(hdfsDemo, hdfsView.status, TeditI, TSaveI, TAllI, TcopyI, TstickupI, TquitI, TcutI, log);
        setContent(area);
        area.setEditable(false);
        area.setMinSize(0, 0);
//        使用时检查文件路径是否正常.
        getGraphic().setOnMouseClicked(event -> chickExists());
        area.setOnMouseClicked(event -> chickExists());
        if (isPreview = hdfsView.status.getLen() / 1024 > 10) {
            prompt();
            log.addLog(2, "文件" + hdfsView.status.getPath().getName() + "超出设定阈值进入预览模式.");
        } else {
            log.addLog(1, "读取文件/" + hdfsView.status.getPath() + "成功.");
        }
        try {
            FSDataInputStream open = hdfsDemo.open(hdfsView.status.getPath());
            BufferedReader reader = new BufferedReader(new InputStreamReader(open));
            String s;
            int line = 0;
            while ((s = reader.readLine()) != null && (!isPreview || ++line < 100)) {
                area.appendText(s + "\n");
                area.old.append(s).append("\n");
            }
            reader.close();
            open.close();
        } catch (IOException e) {
            log.addLog(3, "读取文件/" + hdfsView.status.getPath() + "失败,可能是HDFS发生改动,请刷新后尝试.");
        }
    }

    private void prompt() {
        area.setIsPreview(true);
        choiceColor = Color.SEAGREEN;
        HBox info = new HBox();
        info.setPrefSize(200, 200);
        info.setAlignment(Pos.CENTER);
        info.setStyle("-fx-background-color:black");
        Text name = new Text(hdfsView.status.getPath().getName());
        name.setFont(new Font(30));
        name.setFill(Color.LIGHTGREEN);
        Text text = new Text("文件大小超过预设值只提供预览功能,更多操作请下载到本地.");
        text.setFont(new Font(30));
        text.setFill(Color.WHITE);
        info.getChildren().addAll(name, text);
        root.getChildren().set(2, info);
        AnchorPane.setTopAnchor(info, root.getHeight() / 2 - info.getPrefWidth() / 2);
        AnchorPane.setLeftAnchor(info, root.getWidth() / 2 - info.getPrefHeight() * 2.5);
        FadeTransition ft = new FadeTransition(Duration.seconds(5), info);
        ft.setFromValue(1);
        ft.setToValue(0);
        ft.setOnFinished(event -> root.getChildren().set(2, new HBox()));
        ft.play();
    }

    private boolean chickExists() {
        if (hdfsDemo.exists(path)) return true;
        ErrorPrompt errorPrompt = new ErrorPrompt("路径异常", "你当前所打开的文件或文件路径发生了改变,请刷新后再次尝试");
        log.addLog(2, "/" + hdfsView.status.getPath() + "已经关闭,原因:文件或文件路径发生了改变");
        itemClose();
        errorPrompt.showStage();
        return false;
    }
}
